<?php
namespace Home\Controller;

class ChatController extends HomeController {
    public function index(){
        if($_SESSION['email'] == null){
            $this->error('请登录后进入聊天室',U('Home/login/index'));
        }else{
        //将u_id插入到 chatm表
        $chatonline = M('chatonline');
        $_POST['u_cid'] = $_SESSION['uid'];
        if($_SESSION['nickname']!=null){
            $_POST['u_nickname'] = $_SESSION['nickname'];
        }else{
            $_POST['u_nickname']=$_SESSION['email'];
        }
        $_POST['online'] = time ();
        $result = $chatonline->data($_POST)->add();
        $list = $chatonline->where('status = 0')->select();
        $this->assign('list',$list);
        $email = $_SESSION['email'];
        $u_cid = $_SESSION['uid'];
        $this->assign('email',$email);
        $this->assign('u_cid',$u_cid);
        // var_dump($list);die;
        //将广告遍历
        $ad = M('ad');
        $ads = $ad->where('ad_status = 1')->select();
        // var_dump($ads);die;
        $this->assign('ad',$ads);
        $this->display();
        }
    }
    public function message(){
        $mes = M('chat');
        $time = date('Y-m-d H:i',time());
        $_POST['sendTime'] = $time;
        // $_POST['isget'] = 0;
        $re = $mes->create();
        if($re>0){
            $re = $mes->add();
            if($re>0){
                echo json_encode($re);
            }else{
                echo json_encode('发送失败');
                return false;
            }
        }else{
            echo json_encode('发送失败');
            return false;
        }
    }

    public function getMes(){
        $mes = M('chat');
        // $where['isget'] = 0;
        $array = $mes->order('mesId desc')->limit(50)->select();
        $num = count($mes->select());
        for ($i=0; $i < count($array); $i++) { 
            $row = $array[$i];
            $mesformat .= "<p>
                                <span class='speaker'>
                                <font class='speaker' style='color:red;'>{$row['sender']}</font>
                                说:&nbsp
                                </span>
                                {$row['content']}
                                <span class='floatRight'>{$row['sendTime']}</span>
                          </p>";
        }
        // var_dump($_SESSION);die;
        echo $mesformat;
    }

    public function checkTime(){
        echo $_GET['checkTime'];
        $user = M('chatonline');
        $u_cid= $_SESSION['uid'];
        $cur = time();
        $data['u_cid'] = $u_cid;
        $data['online'] = $cur;
        $re = $user->save($data);
        $cur = intval($cur-10); //3秒内没有发送状态的用户被定义为退出聊天室
        // var_dump($cur);die;
        $where['online'] = array('GT',$cur);
        $res = $user->where($where)->select();
        for ($i=0; $i < count($res); $i++) { 
            $info = $res[$i];
            $li .= "<li><a href='{$info['u_cid']}'>{$info['u_nickname']}</a></li>";
        }
        echo $li;
    }

}